<?php
class Category_Model extends CI_Model {

	var $id;
	var $gmt_create;
	var $creator;
	var $gmt_modified;
	var $modifier;
	var $name;
	var $description;
	var $category_type_id;
	var $parent_category_id;
	var $order_no = 0;

	public function __construct() {
		$this->load->database();
	}

	/**
	 * 查询父id下记录
	 */
	public function getByParentId($parent_id) {

		$query = $this->db->query("SELECT * FROM category WHERE parent_category_id=".$parent_id." ORDER BY order_no ;");

		return $query->result_array();
	}

	/**
	 * 按id进行查询
	 */
	public function get($id){
		$query = $this->db->get_where('category', array('id'=>$id));
		return $query->row();
	}

	/**
	 * 返回ztree需要的json串
	 */
	public function getTreeJson($parent_id){

		//最后返回结果
		$json = "[";

		if(empty($parent_id)){
			$parent_id = "0" ;
		}

		//按父id查询出子栏目
		$result_array = $this->getByParentId($parent_id);

		$i = 0 ;
		//遍历所有子栏目
		foreach ($result_array as $row){
			$id = $row['id'];
			$name = $row['name'];
			$categoryType = $row['category_type_id'];

			$categoryTypeName = "";
			if($categoryType == "1"){
				$categoryTypeName = "单篇";
			}
			if($categoryType == "2"){
				$categoryTypeName = "列表";
			}
			if($categoryType == "3"){
				$categoryTypeName = "图片";
			}

			//查找当前栏目是否有子栏目
			$childCount = $this->db->get_where('category', array('parent_category_id'=>$id))->num_rows();

			//文章数量
			$contentCount = $this->db->get_where('content', array('category_id'=>$id))->num_rows();

			if($i == 0){
				$json .= "{ 'id':'" . $id . "' , 'name':'" . $name . "  (" . $categoryTypeName ."类_" . $contentCount . ")" . "' , 'categoryType':'" . $categoryType . "' , 'isParent':" . ($childCount > 0 ? "true":"false") . ",click:true}";
			}else{
				$json .= ",{ 'id':'" . $id . "' , 'name':'" . $name . "  (" . $categoryTypeName ."类_" . $contentCount . ")" . "' , 'categoryType':'" . $categoryType . "' , 'isParent':" . ($childCount > 0 ? "true":"false") . ",click:true}";
			}

			$i++;
		}
		$json .= "]";
		return $json;
	}

	/**
	 * 将自身对象内容保存入库
	 */
	public function save(){

		if($this->gmt_create == null) {

		}

		if($this->gmt_modified == null) {
			$this->gmt_modified = date("Y-m-d H:i:s", time());
		}

		$this->db->insert('category', $this);
	}

	/**
	 * 将传入内容更新入库
	 */
	public function update($id , $category) {
		$this->db->where('id', $id)->update('category', $category);
	}

	/**
	 * 从数据库删除一条记录
	 */
	public function delete($categoryId) {

		$this->db->delete('category', array('id' => $categoryId));
		return true ;

	}
}
?>